from django.core.files.storage import Storage
from django.conf import settings
from fdfs_client.client import Fdfs_client, get_tracker_conf


class MyStorage(Storage):
    def __init__(self):
        self.base_url = settings.FDFS_BASE_URL

    def _open(self, name, mode='rb'):
        pass

    def _save(self, name, content):
        # 返回 真实存储的 文件名
        # 1. 读取配置文件
        conf = get_tracker_conf(conf_path=settings.FDFS_CONF_PATH)
        # 2. 创建FastDFS客户端实例
        client = Fdfs_client(conf)
        # 3. 调用FastDFS客户端上传文件方法
        ret = client.upload_by_buffer(content.file.read())
        return ret['Remote file_id'].decode()

    def url(self, name):
        return self.base_url + name

    def exists(self, name):
        return False